/**
 * 
 */
package simulation;

import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

/**
 * @author aclayton
 *
 */
public class Obstacle {
	private Point p1,p2,p3;
	private LineSeg seg1, seg2, seg3;
	private Rect boundingBox;
	
	public Obstacle(Point p1, Point p2, Point p3){
		this.p1 = p1;
		this.p2 = p2;
		this.p3 = p3;
		
		this.seg1 = new LineSeg(p1,p2);
		this.seg2 = new LineSeg(p2,p3);
		this.seg3 = new LineSeg(p3,p1);
		
		boundingBox = seg1.getBoundingBox();
		boundingBox = boundingBox.union(seg2.getBoundingBox());
		boundingBox = boundingBox.union(seg3.getBoundingBox());
	}
	
	public ArrayList<Point> getPoints(){
		ArrayList<Point> list = new ArrayList<Point>();
		
		list.add(p1);
		list.add(p2);
		list.add(p3);
		
		return list;
	}
	
	public Rect getBoundingBox(){
		return boundingBox;
	}

	public ArrayList<LineSeg> getSegments(){
		ArrayList<LineSeg> list = new ArrayList<LineSeg>();
		
		list.add(seg1);
		list.add(seg2);
		list.add(seg3);
		
		return list;
	}
	
	public boolean intersectsLine(LineSeg otherseg){
		
		if(!otherseg.intersectBox(boundingBox))
			return false;
		
		//if(boundingBoxotherseg)
		
		for(LineSeg segs : getSegments()){
			if(segs.interectsSeg(otherseg))
				return true;
		}
		return false;
	}
	
	public boolean intersectsCircle(Circle c){
		if(!boundingBox.intersectsRect(c.getBoundingBox()))
			return false;
		
		
		LineSeg tempSeg = new LineSeg(new Point(0,0), c.getCenter());
		int intersections = 0;
		for(LineSeg segs : getSegments()){
			if(c.intersectsLineSeg(segs))
				return true;
			if(tempSeg.interectsSeg(segs))
				intersections++;
		}
		if(intersections == 1)
			return true;
		
		
		return false;
	}
	
	public static Obstacle createFromString(String input){
		/*
		Scanner s = new Scanner(input);
		s.skip("Obstacle");
		while(s.hasNextDouble())
			System.out.println(s.nextDouble());
		*/
		String temp = input;
		String[] strs = temp.split("\\(");
		temp = strs[1];
		strs = temp.split("\\)");
		temp = strs[0];
		strs = temp.split(",");
		
		double nums[] = new double[6];
		
		for(int a = 0; a < 6; a++)
			nums[a] = Double.valueOf(strs[a]);
		
		Point newP1 = new Point(nums[0], nums[1]);
		Point newP2 = new Point(nums[2], nums[3]);
		Point newP3 = new Point(nums[4], nums[5]);
		
		
		
		return new Obstacle(newP1, newP2, newP3);
	}
	
	public String toString(){
		String s = "Obstacle(";
		s = s + p1.getX() + "," + p1.getY() + ",";
		s = s + p2.getX() + "," + p2.getY() + ",";
		s = s + p3.getX() + "," + p3.getY() + ")";
		return s;
	}
	
	public static Obstacle createRandomObstacleInBox(double right, double top, double left, double bottom){
		return new Obstacle(Point.getRandomPointInBox(right, top, left, bottom),
				Point.getRandomPointInBox(right, top, left, bottom),
				Point.getRandomPointInBox(right, top, left, bottom));
		
	}
}
